<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="Socket网络中不同主机上的应用进程之间进行双向通信的端点的抽象。Socket 本身并不是一个协议，而是一个调用接口。它工作在 OSI 模型会话层，是为了方便大家直接使用更底层协议（一般是 TCP 或 UDP ）而存在的一个抽象层。Socket 是对 TCP&#x2F;IP 协议的封装。 Socket 连接流程创建 Socket 的时候，可以指定网络层使用的是 IPv4 还是 IPv6，传输层使">
<meta property="og:type" content="article">
<meta property="og:title" content="Socket">
<meta property="og:url" content="https://vhuichen.github.io/2021/03/NetworkProtocol/Socket/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="Socket网络中不同主机上的应用进程之间进行双向通信的端点的抽象。Socket 本身并不是一个协议，而是一个调用接口。它工作在 OSI 模型会话层，是为了方便大家直接使用更底层协议（一般是 TCP 或 UDP ）而存在的一个抽象层。Socket 是对 TCP&#x2F;IP 协议的封装。 Socket 连接流程创建 Socket 的时候，可以指定网络层使用的是 IPv4 还是 IPv6，传输层使">
<meta property="og:locale">
<meta property="og:image" content="https://gitee.com/vhuichen/images/raw/master/img/20210419122732.png">
<meta property="article:published_time" content="2021-03-18T16:00:00.000Z">
<meta property="article:modified_time" content="2021-07-14T15:24:22.274Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="Socket">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/vhuichen/images/raw/master/img/20210419122732.png">


<link rel="canonical" href="https://vhuichen.github.io/2021/03/NetworkProtocol/Socket/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2021/03/NetworkProtocol/Socket/","path":"2021/03/NetworkProtocol/Socket/","title":"Socket"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Socket | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Socket"><span class="nav-number">1.</span> <span class="nav-text">Socket</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Socket-%E8%BF%9E%E6%8E%A5%E6%B5%81%E7%A8%8B"><span class="nav-number">1.1.</span> <span class="nav-text">Socket 连接流程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#TCP%E6%96%B9%E5%BC%8F-%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="nav-number">1.1.1.</span> <span class="nav-text">TCP方式 服务器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#TCP%E6%96%B9%E5%BC%8F-%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="nav-number">1.1.2.</span> <span class="nav-text">TCP方式 客户端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#UDP%E6%96%B9%E5%BC%8F-%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF"><span class="nav-number">1.1.3.</span> <span class="nav-text">UDP方式 服务器端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#UDP%E6%96%B9%E5%BC%8F-%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="nav-number">1.1.4.</span> <span class="nav-text">UDP方式 客户端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E4%BF%9D%E8%AF%81-Socket-%E7%9A%84%E9%95%BF%E8%BF%9E%E6%8E%A5"><span class="nav-number">1.1.5.</span> <span class="nav-text">如何保证 Socket 的长连接</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2021/03/NetworkProtocol/Socket/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Socket | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Socket
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-03-19 00:00:00" itemprop="dateCreated datePublished" datetime="2021-03-19T00:00:00+08:00">2021-03-19</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2021-07-14 23:24:22" itemprop="dateModified" datetime="2021-07-14T23:24:22+08:00">2021-07-14</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E7%BD%91%E7%BB%9C%E5%8D%8F%E8%AE%AE/" itemprop="url" rel="index"><span itemprop="name">网络协议</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="Socket"><a href="#Socket" class="headerlink" title="Socket"></a>Socket</h1><p>网络中不同主机上的应用进程之间进行双向通信的端点的抽象。<br>Socket 本身并不是一个协议，而是一个调用接口。它工作在 OSI 模型会话层，是为了方便大家直接使用更底层协议（一般是 TCP 或 UDP ）而存在的一个抽象层。Socket 是对 TCP&#x2F;IP 协议的封装。</p>
<h2 id="Socket-连接流程"><a href="#Socket-连接流程" class="headerlink" title="Socket 连接流程"></a>Socket 连接流程</h2><p>创建 Socket 的时候，可以指定网络层使用的是 IPv4 还是 IPv6，传输层使用的是 TCP 还是 UDP。</p>
<img src="https://gitee.com/vhuichen/images/raw/master/img/20210419122732.png" width="500">

<h3 id="TCP方式-服务器"><a href="#TCP方式-服务器" class="headerlink" title="TCP方式 服务器"></a>TCP方式 服务器</h3><ul>
<li>创建套接字（socket）  </li>
<li>将套接字绑定到一个本地地址和端口上（bind）<br>  当内核收到TCP报文，会通过端口号找到对应的Socket</li>
<li>将套接字设为监听模式，准备接收客户端请求（listen）  </li>
<li>等待客户请求到来，当请求到来后，接收连接请求，返回一个新的对应于此次连接的套接字（accept）<br>  监听 Socket 和真正用来传数据的 Socket 是两个，<code>监听 Socket</code> 以及 <code>已连接 Socket</code></li>
<li>用返回的套接字和客户端进行通信（send&#x2F;recv）  </li>
<li>返回，等待另一客户请求  </li>
<li>关闭套接字</li>
</ul>
<p>在 TCP 连接时，内核为每个 Socket 维护两个队列  </p>
<ul>
<li>TCP 半连接队列，还没完全建立连接的队列</li>
<li>TCP 全连接队列，已经建立连接的队列</li>
</ul>
<h3 id="TCP方式-客户端"><a href="#TCP方式-客户端" class="headerlink" title="TCP方式 客户端"></a>TCP方式 客户端</h3><ul>
<li>创建套接字（socket）  </li>
<li>向服务器发出连接请求（connect）  </li>
<li>和服务器端进行通信（send&#x2F;recv）  </li>
<li>关闭套接字</li>
</ul>
<h3 id="UDP方式-服务器端"><a href="#UDP方式-服务器端" class="headerlink" title="UDP方式 服务器端"></a>UDP方式 服务器端</h3><ul>
<li>创建套接字（socket）  </li>
<li>将套接字绑定到一个本地地址和端口上（bind）  </li>
<li>等待接收数据（recvfrom）  </li>
<li>关闭套接字</li>
</ul>
<h3 id="UDP方式-客户端"><a href="#UDP方式-客户端" class="headerlink" title="UDP方式 客户端"></a>UDP方式 客户端</h3><ul>
<li>创建套接字（socket）  </li>
<li>向服务器发送数据（sendto）  </li>
<li>关闭套接字</li>
</ul>
<h3 id="如何保证-Socket-的长连接"><a href="#如何保证-Socket-的长连接" class="headerlink" title="如何保证 Socket 的长连接"></a>如何保证 Socket 的长连接</h3><p>应用层自己实现心跳包</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Socket/" rel="tag"># Socket</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/03/iOS/MVC%E3%80%81MVP%E3%80%81MVVM%E6%A1%86%E6%9E%B6/" rel="prev" title="MVC、MVP、MVVM框架">
                  <i class="fa fa-chevron-left"></i> MVC、MVP、MVVM框架
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/03/NetworkProtocol/%E4%BA%86%E8%A7%A3%20WebSocket/" rel="next" title="了解 WebSocket">
                  了解 WebSocket <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
